

import { createSlice, PayloadAction } from "@reduxjs/toolkit";


export type MediaFile = {
  uri: string,
  type: string
}
export interface GlobalDataState {
  data: AnyObjType,
  imageChoosed: MediaFile[],
  tabBarIsShow:boolean
}


const initialState: GlobalDataState = {
  data: {},
  imageChoosed: [],
  tabBarIsShow: false
};

export const GlobalDataSlice = createSlice({
  name: "globalData",
  initialState,
  reducers: {
    setBgSrc(state, { payload }) {
      state.data["bgSrc"] = payload;
    },
    addMediaChoosed(state, action: PayloadAction<{ uri: string ,type:string}>) {
      const tempImageChoosed = [...state.imageChoosed];
      const hasIndex = tempImageChoosed.findIndex(media=>{
        return media.uri == action.payload.uri;
      });
      if (hasIndex >= 0) {
        tempImageChoosed.splice(hasIndex, 1,action.payload);
      } else {
        tempImageChoosed.push(action.payload);
      }
      state.imageChoosed = tempImageChoosed;
    },
    deleteMediaChoosed(state,action:PayloadAction<number>){
      const tempImageChoosed = [...state.imageChoosed];
      tempImageChoosed.splice(action.payload,1);
      state.imageChoosed = tempImageChoosed;
    },
    replaceMediaChoosed(state,action:PayloadAction<{media:MediaFile,index:number}>){
      if(typeof action.payload.index == "undefined") return;
      const tempImageChoosed = [...state.imageChoosed];
      tempImageChoosed.splice(action.payload.index,1,action.payload.media);
      state.imageChoosed  = tempImageChoosed;
    },
    setTabBarStatus(state,action:PayloadAction<boolean>){
      state.tabBarIsShow = action.payload;
    }
  },
});

export const { setBgSrc, addMediaChoosed,deleteMediaChoosed,replaceMediaChoosed,setTabBarStatus } = GlobalDataSlice.actions;

